package vip.zhenzicheng.nettybasic.outread;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.AllArgsConstructor;

import java.net.InetSocketAddress;
import java.util.logging.Logger;

/**
 * 基于Netty的服务器
 *
 * @author zhenzicheng
 * @date 2022-06-07 19:36
 */
@AllArgsConstructor
public class EchoServerOR {

  private static final Logger LOG = Logger.getLogger(EchoServerOR.class.getSimpleName());

  private final int port;

  public static void main(String[] args) throws InterruptedException {
    int port = 9999;
    EchoServerOR echoServerOR = new EchoServerOR(port);
    LOG.info("服务器即将启动");
    echoServerOR.start();
    LOG.info("服务器关闭");
  }

  public void start() throws InterruptedException {
    // 线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(group)
          .channel(NioServerSocketChannel.class)
          .localAddress(new InetSocketAddress(port))
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) {
              channel.pipeline().addLast(new EchoServerORHandler());
              channel.pipeline().addLast(new ServerOutReadHandler());
            }
          });
      // 异步绑定到服务器
      ChannelFuture future = bootstrap.bind().sync();
      LOG.info("服务器启动完成");
      // 阻塞直到服务器的ServerChannel被关闭
      future.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully().sync();
    }
  }

}
